package com.sh.shanhuo.activity;


import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sh.shanhuo.R;
import com.sh.shanhuo.adapter.TitlesAdapter;
import com.sh.shanhuo.adapter.ToolBoxAdapter;
import com.sh.shanhuo.bean.ToolBoxContentBean;
import com.sh.shanhuo.bean.ToolBoxTitleBean;
import com.sh.shanhuo.listener.GsonObjectCallback;
import com.sh.shanhuo.utils.OkHttpUtil;
import com.sh.shanhuo.utils.ScreenSwitch;
import com.sh.shanhuo.utils.Tools;
import com.sh.shanhuo.view.CommonItemDecoration;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.Call;

public class ToolBoxActivity extends BaseActivity {
    private List<ToolBoxTitleBean.DataBean> titleBean;
    private List<ToolBoxContentBean.RowsBean> rowsBean;
    private ToolBoxAdapter toolBoxAdapter;
    private TitlesAdapter titlesAdapter;
    private int curPageNum;
    private int cateId;
    private TextView searchText;
    private EditText search;
    private SmartRefreshLayout smartLayout;
    private int titlePos;
    private RecyclerView titleItem;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_toolbox;
    }

    @Override
    protected void initView() {
        super.initView();
        ImageView back = findViewById(R.id.back);
        search = findViewById(R.id.search);
        searchText = findViewById(R.id.searchText);
        smartLayout = findViewById(R.id.smartLayout);
        back.setOnClickListener(v -> finish());
        initTitleItem();
        initContentItem();
        smartLayout.setEnableLoadMore(true);
        smartLayout.setEnableRefresh(true);
        smartLayout.setOnLoadMoreListener(refreshLayout -> getSiteList(curPageNum, cateId));
        smartLayout.setOnRefreshListener(refreshLayout -> getSiteList(curPageNum, cateId));

        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                searchText.setText(s.toString());
            }
        });

        search.setOnFocusChangeListener((v, hasFocus) ->{
            if (hasFocus) {
                searchText.setVisibility(View.VISIBLE);
            } else {
                searchText.setVisibility(View.GONE);
            }
        });


        searchText.setOnClickListener(v -> {
            searchText.setVisibility(View.GONE);
            search.clearFocus();
            if (searchText.getText().length() > 0) {
                Bundle bundle = new Bundle();
                bundle.putString("searchText", searchText.getText().toString());
                bundle.putInt("fromFlag", 2);
                ScreenSwitch.startActivity(ToolBoxActivity.this, SearchActivity.class, bundle);
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        searchText.setVisibility(View.GONE);
        search.clearFocus();
    }

    @Override
    protected void onResume() {
        super.onResume();
        search.setText("");
        smartLayout.autoRefresh();
    }

    private float x;
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            x = ev.getX();
            Rect viewRect = new Rect();
            searchText.getGlobalVisibleRect(viewRect);
            if (!viewRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
                search.clearFocus();
            }
        }
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            if (x - ev.getX() > 150) {
                if (titlePos == titleBean.size() - 1)
                    return super.dispatchTouchEvent(ev);
                titlePos += 1;
                titleItem.smoothScrollToPosition(titlePos);
                titlesAdapter.setCurPos(titlePos);
                getSiteList(0, titleBean.get(titlePos).getId());
                return true;
            }
            if (x - ev.getX() < -150) {
                if (titlePos == 0)
                    return super.dispatchTouchEvent(ev);
                titlePos -= 1;
                titleItem.smoothScrollToPosition(titlePos);
                titlesAdapter.setCurPos(titlePos);
                getSiteList(0, titleBean.get(titlePos).getId());
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void initTitleItem() {
        titleItem = findViewById(R.id.titleItem);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        titlesAdapter = new TitlesAdapter(this, titleBean);
        titleItem.setLayoutManager(manager);
        titleItem.setAdapter(titlesAdapter);
        titlesAdapter.setOnItemClickListener((adapter, view, position) -> {
            titlesAdapter.setCurPos(position);
            getSiteList(0, titleBean.get(position).getId());
        });
        getCateList();
    }

    private void getCateList() {
        OkHttpUtil.getInstance().postString(OkHttpUtil.IP + OkHttpUtil.GET_CATE_LIST, "", new GsonObjectCallback<ToolBoxTitleBean>() {
            @Override
            public void onUi(ToolBoxTitleBean toolBoxTitleBean) {
                if (toolBoxTitleBean.getData() != null) {
                    titleBean = toolBoxTitleBean.getData();
                    titlesAdapter.setNewData(titleBean);
                    if (toolBoxTitleBean.getData().size() > 0) {
                        cateId = toolBoxTitleBean.getData().get(0).getId();
                    }
                    smartLayout.autoLoadMore();
                }
            }

            @Override
            public void onFailed(Call call, IOException e) {
                ToastUtils.showShort("请求失败，请检查网络错误");
            }
        });
    }

    private void getSiteList(int pageNum, int cateId) {
        this.cateId = cateId;
        Map<String, String> params = new HashMap<>();
        params.put("pageSize", "20");
        params.put("pageNum", pageNum + "");
        params.put("orderByColumn", "");
        params.put("isAsc", "");
        params.put("webName", "");
        params.put("cateId", cateId + "");
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.GET_SITES, params, new GsonObjectCallback<ToolBoxContentBean>() {
            @Override
            public void onUi(ToolBoxContentBean toolBoxContentBean) {
                smartLayout.finishLoadMore();
                smartLayout.finishRefresh();
                rowsBean = toolBoxContentBean.getRows();
                if (toolBoxAdapter != null) {
                    toolBoxAdapter.setNewData(rowsBean);
                }
                curPageNum += toolBoxContentBean.getTotal();
            }

            @Override
            public void onFailed(Call call, IOException e) {
                ToastUtils.showShort("请求失败，请检查网络错误");
            }
        });
    }

    private void initContentItem() {
        RecyclerView contentItem = findViewById(R.id.contentItem);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        contentItem.setLayoutManager(manager);
        contentItem.addItemDecoration(new CommonItemDecoration(Tools.dp2px(mContext, 10),
                Tools.dp2px(mContext, 10), Tools.dp2px(mContext, 10)));
        toolBoxAdapter = new ToolBoxAdapter(this, rowsBean);
        contentItem.setAdapter(toolBoxAdapter);
        toolBoxAdapter.setOnItemClickListener((adapter, view, position) -> {
            Bundle bundle = new Bundle();
            bundle.putString("id", rowsBean.get(position).getId());
            bundle.putString("webName", rowsBean.get(position).getWebName());
            bundle.putString("logoUrl", rowsBean.get(position).getLogoUrl());
            bundle.putString("introduce", rowsBean.get(position).getIntroduce());
            bundle.putString("webUrl", rowsBean.get(position).getWebUrl());
            bundle.putString("abstraction", rowsBean.get(position).getAbstraction());
            ScreenSwitch.startActivity(ToolBoxActivity.this,
                    RecommendationInfoActivity.class, bundle);
        });
    }
}
